import { request } from "../../request/index.js";
import regeneratorRuntime from '../../lib/runtime/runtime.js';
Page({
  data: {
    leftMenuList: [],
    rightContentList: [],
    // 当前索引，功能：控制左侧菜单栏选中
    currentIndex:0,
    currentDistance:0
  },
  Cates: [],

  checkIndex: function(e){
    // console.log(e) => 从e.currentTarget.dataset结构 index属性
    const {index} = e.currentTarget.dataset;
    // const currentIndex = index;
    let rightContentList = this.Cates[index].children;

    this.setData({
      currentIndex: index,
      rightContentList,
      currentDistance:0
    })
  },

  onLoad: function (options) {
    /* 发获取数据的异步请求每次耗时过长，用缓存技术
        1. 判断是否有缓存数据
        2. 若没有缓存数据，直接发请求
        3. 若有缓存数据，且没有过期，则用缓存数据渲染页面
     */
    // this.getCatData();

    const Cates = wx.getStorageSync("cates");
    if(!Cates){
      // 表示不存在key为cates的本地缓存
      this.getCatData();
    }else{
      if(Date.now()-Cates.time > 1000*10){
        // 虽然有缓存，但是过期，重新发送请求
        this.getCatData();
      }else{
        // console.log(Cates)
        // 有缓存可以用，先把缓存赋给数据Cates
        this.Cates = Cates.data;
        let leftMenuList = this.Cates.map(v => v.cat_name);
        let rightContentList = this.Cates[0].children;
        this.setData({
          leftMenuList,
          rightContentList
        })
      }
    }
    
  },

  async getCatData() {
    // request({
    //   url: "/categories"
    // }).then(result => {
    //   console.log(result)
    //   this.Cates = result.data.message;
    //   // 发送请求获得异步数据成功后将数据写入缓存
    //   wx.setStorageSync("cates", {time:Date.now(), data:this.Cates});

    //   let leftMenuList = this.Cates.map(v => v.cat_name);
    //   let rightContentList = this.Cates[0].children;
    //   this.setData({
    //     leftMenuList,
    //     rightContentList
    //   })
    // })


    const result = await request({url:"/categories"});
    this.Cates = result;
      // 发送请求获得异步数据成功后将数据写入缓存
    wx.setStorageSync("cates", {time:Date.now(), data:this.Cates});

    let leftMenuList = this.Cates.map(v => v.cat_name);
    let rightContentList = this.Cates[0].children;
    this.setData({
      leftMenuList,
      rightContentList
    })

  }
})